﻿using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
using UnityEngine;
using UnityEngine.UI;

namespace DG.Tweening
{
    public static class DOTweenExtend
    {
        public static Tweener DOAlpha(this Transform target, float endAlpha, bool includeChildren = true)
        {
            return target.DOAlpha(-1, endAlpha, 0, Ease.Linear, includeChildren);
        }

        public static Tweener DOAlpha(this Transform target, float endAlpha, float duration, Ease ease, bool includeChildren = true)
        {
            return target.DOAlpha(-1, endAlpha, duration, ease, includeChildren);
        }

        public static Tweener DOAlpha(this Transform target, float beginAlpha, float endAlpha, float duration, Ease ease, bool includeChildren = true)
        {
            if (includeChildren)
            {
                CanvasGroup canvasGroup = target.GetComponent<CanvasGroup>();
                if (!canvasGroup) canvasGroup = target.gameObject.AddComponent<CanvasGroup>();
                if (duration > 0f)
                {
                    if (beginAlpha != -1)
                    {
                        canvasGroup.alpha = beginAlpha;
                    }
                    return canvasGroup.DOFade(endAlpha, duration);
                }
                else
                {
                    canvasGroup.alpha = endAlpha;
                }
            }
            else
            {
                Graphic graphic = target.GetComponent<Graphic>();
                if (graphic)
                {
                    Color color = graphic.color;
                    if (duration > 0f)
                    {
                        if (beginAlpha != -1)
                        {
                            color.a = beginAlpha;
                            graphic.color = color;
                        }
                        return graphic.DOFade(endAlpha, duration);
                    }
                    else
                    {
                        color.a = endAlpha;
                        graphic.color = color;
                    }
                }
            }
            return null;
        }

        public static void DOKillAlpha(this Transform target)
        {
            CanvasGroup canvasGroup = target.GetComponent<CanvasGroup>();
            if (canvasGroup)
            {
                canvasGroup.DOKill();
            }
            else
            {
                Graphic graphic = target.GetComponent<Graphic>();
                if (graphic)
                {
                    graphic.DOKill();
                }
            }
        }

    }
}